<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Comments_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    
    function getComments(array $param, $page=0, $limit=20)
    {
        if(!isset($param['field']) || empty($param['field']))
        {
            
            $param['field'] = '*';
        }

        $this->db->select($param['field']);
        $this->db->from('comments c');
        $this->db->join('users u', 'c.authorId=u.uid', 'left');
        if(isset($param['where']) && ! empty($param['where']))
        {
            $this->db->where($param['where']);
        }
        if(isset($param['like']) && ! empty($param['like']))
        {
            $this->db->like($param['like']);
        }
        if(!isset($param['order']) || empty($param['order']))
        {
            $param['order']='cdtime desc';
        }
        
        $this->db->order_by($param['order']);
        $this->db->limit($limit, $page);
        return $this->db->get()->result_array();
    }
    
    function add(array $comments)
    {
        /** 构建插入结构 */
        $insertStruct = array(
            'cdtime'    =>  time(),
            'status'        =>  'approved',
            'agent'    =>  $comments['answers_agent'],
            'type'    =>  empty($comments['answers_type']) ? 'none' : $comments['answers_type'],
            'mail'       =>  $comments['answers_mail'],
            'ip'        =>  $comments['answers_ip'],
            'cid'        =>  $comments['answers_id'],
            'text'   =>  empty($comments['answers_content']) ? NULL : $comments['answers_content'],
        );
        if($this->session->userdata('uid'))
            $insertStruct['authorId'] = $this->session->userdata('uid');
        else
            $insertStruct['author'] = $comments['answers_name'];
                
        /** 首先插入部分数据 */
        $this->db->insert('comments', $insertStruct);
        $insertId = $this->db->insert_id();
        
        /** keyword 
        if($insertId > 0 && !empty($comments['answers_tag']))
        {
            $this->load->model('Tags');
            $this->Tags->add_Answers($insertId, $comments['answers_tag']);
        }
        */
        return $insertId;
    }
    
    
    public function deleteAnswers($answers_id)
    {
        //删除tag关联
        $this->load->model('Tags');
        $this->Tags->deleteAnswers($answers_id);
                
        //删除Answers
        return $this->db->delete('answers', array('answers_id' => $answers_id));
    }
}